package http;

import com.dx.as.JWCache;
import com.dx.as.LoadingDialog;
import com.dx.as.common.CommonUtils;
import com.dx.as.common.JWResult;
import com.dx.as.common.log.LogUtil;
import com.dx.as.common.string.StringUtil;
import com.dx.as.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by jwaoo on 2017/5/25.
 */

public class HttpClientHelper {
    private static Retrofit retrofit ;
    private static Gson gson = new Gson();
    public static void doNet(Call call , final IHttpListener listener , TypeToken typeToken){
        CommonUtils.addTypeToken(call.hashCode(),typeToken);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                int hasCode = call.hashCode();
                boolean isSuccess = false;
                if (response != null){
                    try {
                        ResponseBody myResponse = null;
                        if (response.code() == HttpCode.HTTP_SUCCESS){
                            isSuccess = true;
                            myResponse = response.body();
                        }else if (response.code() == HttpCode.BAD_REQUEST){
                            myResponse = response.errorBody();
                        }else {
                            listener.onFilure(response.code(),HttpCode.getHttpErrorMsg(response.code()));
                        }
                        if (myResponse != null){
                            String body = myResponse.string();
                            LogUtil.d("http",body);
                            if (!Utils.isEmpty(body)){
                                JWResult<Object> result;
                                if (isSuccess)
                                    result = gson.fromJson(body, CommonUtils.getType(hasCode));
                                else result = gson.fromJson(body,new TypeToken<JWResult<Object>>(){}.getType());
                                if (result != null){
                                    if (result.getCode() == HttpCode.REQUEST_SUCCESS){
                                        listener.onResponse(result.getRst(),hasCode);
                                    }else {
                                        listener.onFilure(result.getCode(),HttpCode.getHttpErrorMsg(result.getCode()));
                                    }
                                }
                            }
                        }
                    }catch (Exception ex){
                        ex.printStackTrace();
                    }
                }
                CommonUtils.removeTypeToken(hasCode);
                LoadingDialog.getInstance(JWCache.getContext()).dismiss();
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
                LogUtil.d("http",t.toString());
                if (call != null)
                    CommonUtils.removeTypeToken(call.hashCode());
                if (call != null && !call.isCanceled()){
                    listener.onFailure(t);
                }
                //网络请求失败时总的处理方法
                LoadingDialog.getInstance(JWCache.getContext()).dismiss();
            }
        });
    }

    public static Retrofit getRetrofit(){
        if (retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl("http://47.52.108.190/")
                    //http://192.168.10.97:8080/
//                    .baseUrl("http://192.168.10.241/")
//                    .baseUrl("http://192.168.10.97:808s0/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build(interceptor);
        }
        return retrofit;
    }

    private static Interceptor interceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            // Request customization: add request headers
            String deviceNo = CommonUtils.getDeviceInfo().getDevice_no();
            Request.Builder requestBuilder = original.newBuilder()
                    .addHeader("Client-Type","1")
                    .addHeader("Device-No", "869915020116892")//StringUtil.isEmpty(deviceNo) ? "test":deviceNo )//869915020116892
                    .addHeader("Mac", CommonUtils.getDeviceInfo().getMac() == null ?"":CommonUtils.getDeviceInfo().getMac())
                    .addHeader("OS-Type", CommonUtils.getDeviceInfo().getOs_type())
                    .addHeader("OS-Version", CommonUtils.getDeviceInfo().getOs_version())
                    .addHeader("Hard-Ware", "ZTE ZTE A2017")//CommonUtils.getDeviceInfo().getHard_ware())//ZTE ZTE A2017
                    .addHeader("Channel-ID", "598838d37435cf7fc9105129")
                    .addHeader("Client-ID", "598837f87435cf7fc9105126")
//                   .addHeader("Channel-ID", "5969d6211929b03a83578e74")
//                    .addHeader("Client-ID", "5972c401a210fecf8929b714")

                    .addHeader("Version", CommonUtils.getDeviceInfo().getVersion())
                    .addHeader("Network-Mode", StringUtil.isEmpty(JWCache.getNetworkMode()) ? "" :JWCache.getNetworkMode())
                    .addHeader("x-auth-token", StringUtil.isEmpty(JWCache.getToken()) ? "" : JWCache.getToken())
                    .addHeader("Content-Type","application/json")
                    .addHeader("Hedno","test");//URLEncoder.encode(CommonUtils.getDeviceInfo().getHedno(),"UTF-8"));
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    };

}
